package jnpf.service.impl;

import jnpf.entity.*;
import jnpf.mapper.RelationMangeMapper;
import jnpf.model.template.relationVO;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.relationmange.*;
import java.math.BigDecimal;
import cn.hutool.core.util.ObjectUtil;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.util.GeneraterSwapUtil;
import jnpf.database.model.superQuery.SuperQueryJsonModel;
import jnpf.database.model.superQuery.ConditionJsonModel;
import jnpf.database.model.superQuery.SuperQueryConditionModel;
import java.lang.reflect.Field;
import com.baomidou.mybatisplus.annotation.TableField;
import java.util.regex.Pattern;
import jnpf.model.QueryModel;
import java.util.stream.Collectors;
import jnpf.base.model.ColumnDataModel;
import jnpf.util.UserProvider;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jnpf.database.model.superQuery.SuperJsonModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.text.SimpleDateFormat;
import jnpf.util.*;
import java.util.*;
import jnpf.base.UserInfo;
import jnpf.permission.entity.UserEntity;
/**
 *
 * relationMange
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-04-11
 */
@Service
public class RelationMangeServiceImpl extends ServiceImpl<RelationMangeMapper, RelationMangeEntity> implements RelationMangeService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;



    @Override
    public List<RelationMangeEntity> getList(RelationMangePagination relationMangePagination){
        return getTypeList(relationMangePagination,relationMangePagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<RelationMangeEntity> getTypeList(RelationMangePagination relationMangePagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
        List<List<String>> intersectionList =new ArrayList<>();
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ? RelationMangeConstant.getAppColumnData() : RelationMangeConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());

        int total=0;
        int relationMangeNum =0;
        QueryWrapper<RelationMangeEntity> relationMangeQueryWrapper=new QueryWrapper<>();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp ="";
        if (ObjectUtil.isNotEmpty(relationMangePagination.getSuperQueryJson())){
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList  = new ArrayList<>();
            String queryJson = relationMangePagination.getSuperQueryJson();
            SuperJsonModel superJsonModel = JsonUtil.getJsonToBean(queryJson, SuperJsonModel.class);
            int superNum = 0;
            QueryWrapper<RelationMangeEntity> relationMangeSuperWrapper = new QueryWrapper<>();
            relationMangeSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(relationMangeSuperWrapper,RelationMangeEntity.class,queryJson,"0"));
            int relationMangeNum1 = relationMangeSuperWrapper.getExpression().getNormal().size();
            if (relationMangeNum1>0){
                List<String> relationMangeList =this.list(relationMangeSuperWrapper).stream().map(RelationMangeEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(relationMangeList);
                intersectionSuperList.add(relationMangeList);
                superNum++;
            }
            superOp = superNum > 0 ? superJsonModel.getMatchLogic() : "";
            //and or
            if(superOp.equalsIgnoreCase("and")){
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            }else{
                allSuperIDlist = allSuperList;
            }
        }
        List<String> allRuleIDlist = new ArrayList<>();
        String ruleOp ="";
        if (ObjectUtil.isNotEmpty(ruleJson)){
            List<String> allRuleList = new ArrayList<>();
            List<List<String>> intersectionRuleList  = new ArrayList<>();
            SuperJsonModel ruleJsonModel = JsonUtil.getJsonToBean(ruleJson, SuperJsonModel.class);
            int ruleNum = 0;
            QueryWrapper<RelationMangeEntity> relationMangeSuperWrapper = new QueryWrapper<>();
            relationMangeSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(relationMangeSuperWrapper,RelationMangeEntity.class,ruleJson,"0"));
            int relationMangeNum1 = relationMangeSuperWrapper.getExpression().getNormal().size();
            if (relationMangeNum1>0){
                List<String> relationMangeList =this.list(relationMangeSuperWrapper).stream().map(RelationMangeEntity::getId).collect(Collectors.toList());
                allRuleList.addAll(relationMangeList);
                intersectionRuleList.add(relationMangeList);
                ruleNum++;
            }
            ruleOp = ruleNum > 0 ? ruleJsonModel.getMatchLogic() : "";
            //and or
            if(ruleOp.equalsIgnoreCase("and")){
                allRuleIDlist = generaterSwapUtil.getIntersection(intersectionRuleList);
            }else{
                allRuleIDlist = allRuleList;
            }
        }
    boolean pcPermission = false;
    boolean appPermission = false;
    if(isPc && pcPermission){
    if (!userProvider.get().getIsAdministrator()){
        Object relationMangeObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(relationMangeQueryWrapper,RelationMangeEntity.class,relationMangePagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(relationMangeObj)){
        return new ArrayList<>();
        } else {
        relationMangeQueryWrapper = (QueryWrapper<RelationMangeEntity>)relationMangeObj;
        if( relationMangeQueryWrapper.getExpression().getNormal().size()>0){
        relationMangeNum++;
        }
        }
    }
    }
    if(!isPc && appPermission){
    if (!userProvider.get().getIsAdministrator()){
        Object relationMangeObj=generaterSwapUtil.getAuthorizeCondition(new QueryModel(relationMangeQueryWrapper,RelationMangeEntity.class,relationMangePagination.getMenuId(),"0"));
        if (ObjectUtil.isEmpty(relationMangeObj)){
        return new ArrayList<>();
        } else {
        relationMangeQueryWrapper = (QueryWrapper<RelationMangeEntity>)relationMangeObj;
        if( relationMangeQueryWrapper.getExpression().getNormal().size()>0){
        relationMangeNum++;
        }
        }


    }
    }
        if(isPc){
            if(ObjectUtil.isNotEmpty(relationMangePagination.getDirection())){
            relationMangeNum++;

        List<String> idList = new ArrayList<>();
        try {
        String[][] direction = JsonUtil.getJsonToBean(relationMangePagination.getDirection(),String[][].class);
        for(int i=0;i<direction.length;i++){
        if(direction[i].length>0){
        idList.add(JsonUtil.getObjectToString(Arrays.asList(direction[i])));
        }
        }
        }catch (Exception e1){
        try {
        List<String> direction = JsonUtil.getJsonToList(relationMangePagination.getDirection(),String.class);
        if(direction.size()>0){
            idList.addAll(direction);
        }
        }catch (Exception e2){
        idList.add(String.valueOf(relationMangePagination.getDirection()));
        }
        }
        relationMangeQueryWrapper.lambda().and(t->{
        idList.forEach(tt->{
        t.like(RelationMangeEntity::getDirection, tt).or();
        });
        });

            }

            if(ObjectUtil.isNotEmpty(relationMangePagination.getCreateTime())){
            relationMangeNum++;

                List CreateTimeList =  JsonUtil.getJsonToList(relationMangePagination.getCreateTime(),String.class);
                    Long fir = Long.valueOf(String.valueOf(CreateTimeList.get(0)));
                    Long sec = Long.valueOf(String.valueOf(CreateTimeList.get(1)));

                    relationMangeQueryWrapper.lambda().ge(RelationMangeEntity::getCreateTime, new Date(fir))
                    .le(RelationMangeEntity::getCreateTime, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));


            }

            if(ObjectUtil.isNotEmpty(relationMangePagination.getRelationId())){
            relationMangeNum++;

                String value = relationMangePagination.getRelationId() instanceof List ?
                    JsonUtil.getObjectToString(relationMangePagination.getRelationId()) :
                    String.valueOf(relationMangePagination.getRelationId());
                relationMangeQueryWrapper.lambda().like(RelationMangeEntity::getRelationId,value);

            }

        }
        if(!isPc){
            if(ObjectUtil.isNotEmpty(relationMangePagination.getRelationId())){
            relationMangeNum++;

                String value = relationMangePagination.getRelationId() instanceof List ?
                    JsonUtil.getObjectToString(relationMangePagination.getRelationId()) :
                    String.valueOf(relationMangePagination.getRelationId());
                relationMangeQueryWrapper.lambda().like(RelationMangeEntity::getRelationId,value);

            }

        }
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total>0){
            if (intersection.size()==0){
                intersection.add("jnpfNullList");
            }
            relationMangeQueryWrapper.lambda().in(RelationMangeEntity::getId, intersection);
        }
    //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)){
            if (allSuperIDlist.size()==0){
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            relationMangeQueryWrapper.lambda().and(t->t.in(RelationMangeEntity::getId, finalAllSuperIDlist));
        }
    //是否有数据过滤查询
        if (StringUtil.isNotEmpty(ruleOp)){
            if (allRuleIDlist.size()==0){
                allRuleIDlist.add("jnpfNullList");
            }
            List<String> finalAllRuleIDlist = allRuleIDlist;
            relationMangeQueryWrapper.lambda().and(t->t.in(RelationMangeEntity::getId, finalAllRuleIDlist));
        }

        //排序
        if(StringUtil.isEmpty(relationMangePagination.getSidx())){
            relationMangeQueryWrapper.lambda().orderByDesc(RelationMangeEntity::getId);
        }else{
            try {
                String sidx = relationMangePagination.getSidx();
                String[] strs= sidx.split("_name");
                RelationMangeEntity relationMangeEntity = new RelationMangeEntity();
                Field declaredField = relationMangeEntity.getClass().getDeclaredField(strs[0]);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                relationMangeQueryWrapper="asc".equals(relationMangePagination.getSort().toLowerCase())?relationMangeQueryWrapper.orderByAsc(value):relationMangeQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<RelationMangeEntity> page=new Page<>(relationMangePagination.getCurrentPage(), relationMangePagination.getPageSize());
                IPage<RelationMangeEntity> userIPage=this.page(page, relationMangeQueryWrapper);
                return relationMangePagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<RelationMangeEntity> list = new ArrayList();
                return relationMangePagination.setData(list, list.size());
            }
        }else{
            return this.list(relationMangeQueryWrapper);
        }
    }
    @Override
    public RelationMangeEntity getInfo(String id){
        QueryWrapper<RelationMangeEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(RelationMangeEntity::getId,id);
        return this.getOne(queryWrapper);
    }
    @Override
    public void create(RelationMangeEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String id, RelationMangeEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(RelationMangeEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(RelationMangeForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id="";
        String countRecover = "";
        if (isUp){
            id = form.getId();
        }
        //主表字段验证
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param relationMangeForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(RelationMangeForm relationMangeForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        relationMangeForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(RelationMangeConstant.getFormData(),relationMangeForm),RelationMangeForm.class);
        RelationMangeEntity entity = JsonUtil.getJsonToBean(relationMangeForm, RelationMangeEntity.class);

        if(isSave){
            String mainId =  RandomUtil.uuId() ;
        entity.setCreateTime(DateUtil.getNowDate());
        entity.setCreateUserId(userInfo.getUserId());
            entity.setId(mainId);
        }else{
        entity.setCreateTime(DateUtil.getNowDate());
        entity.setCreateUserId(userInfo.getUserId());
        }
        this.saveOrUpdate(entity);

    }

    @Override
    public List<relationVO> getRelationVOList(String id) {
        // 1. 查询子表数据(relation_content表)
        QueryWrapper<RelationMangeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(RelationMangeEntity::getEntityId, id);
        List<RelationMangeEntity> relationContentList = this.list(queryWrapper);

        if(relationContentList.isEmpty()){
            return new ArrayList<>();
        }

        // 2. 组合结果
        List<relationVO> result = new ArrayList<>();
        for (RelationMangeEntity content : relationContentList) {
            relationVO vo = new relationVO();
            // 设置父表ID
            vo.setRelationId(content.getRelationId());
            // 设置子表字段
            vo.setEntityId(content.getEntityId());
            vo.setTargetEntityId(content.getTargetEntityId());
            vo.setDirection(content.getDirection());
            vo.setTagId(content.getTagId());
            result.add(vo);
        }

        return result;
    }
}
